package cn.aifeix.product.service.impl;

import cn.aifeix.basic.config.BussinessException;
import cn.aifeix.basic.util.BaiduAuditUtils;
import cn.aifeix.basic.util.CodeGenerateUtils;
import cn.aifeix.order.domain.OrderProduct;
import cn.aifeix.order.service.IOrderProductService;
import cn.aifeix.product.domain.Product;
import cn.aifeix.product.domain.ProductDetail;
import cn.aifeix.product.domain.ProductOnlineAuditLog;
import cn.aifeix.product.domain.Product;
import cn.aifeix.product.domain.ProductDetail;
import cn.aifeix.product.dto.goBuyDto;
import cn.aifeix.product.mapper.ProductMapper;
import cn.aifeix.product.service.IProductDetailService;
import cn.aifeix.product.service.IProductOnlineAuditLogService;
import cn.aifeix.product.service.IProductService;
import cn.aifeix.basic.service.impl.BaseServiceImpl;
import cn.aifeix.user.domain.User;
import cn.aifeix.user.service.IUserService;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author aifeix
 * @since 2022-11-03
 */
@Service
public class ProductServiceImpl extends BaseServiceImpl<Product> implements IProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private IProductDetailService productDetailService;

    @Autowired
    private IProductOnlineAuditLogService productOnlineAuditLogService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IOrderProductService orderProductService;
    @Override
    @Transactional
    public void add(Product product) {
        super.add(product);
        ProductDetail productDetail = null;
        if (product.getDetail() == null){
            productDetail = new ProductDetail();
        }else {
            productDetail =  product.getDetail();
        }
        productDetail.setProductId(product.getId());
        productDetailService.add(productDetail);
    }

    @Override
    public Product getProductDetail(Long id) {
        return productMapper.getProductDetail(id);
    }

    /**
     * 上架
     * @param ids
     */
    @Override
    public void onsale(List<Long> ids) {
        // 先过滤点上架状态的数据 把数据转成map k 主键 v对象
        Map<Long, Product> productMaps = productMapper.findAll().stream().filter(product -> product.getState() == 0)
                .collect(Collectors.toMap(Product::getId, product -> product));
        Date date = new Date();
        for (Long id : ids) {
            Product product = productMaps.get(id);
            StringBuilder sb = new StringBuilder();
            if (null != product){
                if (!BaiduAuditUtils.TextCensor(product.getName())){
                    sb.append("宠物上架百度AI审核名称失败，宠物名称为：" + product.getName() + ";");
                }
                if (product.getResources().split(",").length > 1){
                    if (!BaiduAuditUtils.ImgCensor(product.getResources().split(",")[0])){
                        sb.append("宠物上架百度AI审核图片失败，宠物图片地址为：" + product.getResources() + ";");
                    }
                }else {
                    if (!BaiduAuditUtils.ImgCensor(product.getResources())){
                        sb.append("宠物上架百度AI审核图片失败，宠物图片地址为：" + product.getResources() + ";");
                    }
                }
                if (sb.length() > 0){
                    ProductOnlineAuditLog productOnlineAuditLog = new ProductOnlineAuditLog();
                    productOnlineAuditLog.setAuditTime(date);
                    productOnlineAuditLog.setProductId(id);
                    productOnlineAuditLog.setNote(sb.toString());
                    productOnlineAuditLog.setState(0);
                    productOnlineAuditLogService.add(productOnlineAuditLog);
                    throw new BussinessException("所选上架:"+product.getName()+"-含违规内容，请检查后重新上架");
                }
                product.setState(1L);
                product.setOnsaletime(date);
                productMapper.update(product);
                // 成功则添加到日志表
                ProductOnlineAuditLog productOnlineAuditLog = new ProductOnlineAuditLog();
                productOnlineAuditLog.setAuditTime(date);
                productOnlineAuditLog.setProductId(id);
                productOnlineAuditLog.setNote("审核通过");
                productOnlineAuditLog.setState(1);
                productOnlineAuditLogService.add(productOnlineAuditLog);
            }
        }     
    }

    /**
     * 下架
     * @param ids
     */
    @Override
    public void offsale(List<Long> ids) {
        // 不管之前是啥状态，统一批量下架处理
        productMapper.batchOffsale(ids);
    }

    /**
     * 购买服务
     * @param dto
     */
    @Override
    public void goBuy(goBuyDto dto) {
        // 根据id查询购买的服务信息
        Product product = productMapper.findById(dto.getId());
        if (null == product){
            throw new BussinessException("产品信息不存在");
        }
        // 获取买家的信息
        User user = userService.findByLogininfoId(dto.getLogininfo().getId());
        if (null == user){
            throw new BussinessException("买家信息不存在");
        }
        // 订单生成
        OrderProduct orderProduct = OrderProduct.builder()
                .digest(product.getName())
                .state(0)
                .orderSn(CodeGenerateUtils.generateOrderSn(user.getId()))
                .price(product.getSaleprice())
                .productId(dto.getId())
                .userId(user.getId())
                .build();
        orderProductService.add(orderProduct);
    }
}
